<?php
namespace frontend\models;

use common\models\User;
use common\WuMing;
use yii\base\ErrorException;
use yii\base\Model;
use Yii;
use common\models\Post;

/**
 * Post form
 */
class UrlForm extends Model
{
    public $title;
    public $cid3;
    public $content;
    public $url;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required', 'message' => '请输入标题'],
            [['cid3'], 'required', 'message' => '请选择分类'],
            [['url'], 'required', 'message' => '请填写链接'],
            [['content'], 'safe'],
            [['cid3'], 'integer'],
            [['title'], 'string', 'max' => 255],

            [['url'], 'string', 'max' => 255],
            [['url'], 'url'],
        ];
    }


    public function createPost()
    {
        if ($this->validate()) {
            $user = User::findOne(Yii::$app->user->id);
            //登录用户发帖45秒间隔限制
//            if (time() - $user->last_post < 45) {
//                return false;
//            }
            $user->last_post = time();
            $user->save();
            //保存用的发布的文章
            $post = new Post();
            $post->title = htmlspecialchars($this->title) ;
            $post->content = htmlspecialchars($this->content).".";
            $post->cate_id = $this->cid3;
            $post->user_id = Yii::$app->user->id;
            //测试方便 发布时改为0
            $post->status = 1;
            $post->ip_address = Yii::$app->request->getUserIP();
            $post->signature = $user->signature;
            $post->nickname = $user->nickname;
            $post->img = $user->img;
            $post->create_at = time();
            $post->url = $this->url;

            $res = WuMing::GrabImage($this->url);
            if ($res) {
                $post->thumb = $res;
            }else{
                $post->thumb =null;
            }

            $post->type = 3;

            //如果发布成功  跳转到帖子详情页
            if ($post->save()) {
                return $post;
            }
        }
        return false;
    }
}
